package com.yunji.news.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunji.news.common.Result;
import com.yunji.news.entity.School;
import com.yunji.news.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 管理后台-院校管理控制器
 *
 * @author yunji
 * @since 2024-11-23
 */
@RestController
@RequestMapping("/admin/schools")
@CrossOrigin
public class AdminSchoolController {
    
    @Autowired
    private SchoolService schoolService;
    
    /**
     * 分页查询院校列表
     */
    @GetMapping
    public Result<IPage<School>> getSchools(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String schoolType) {
        
        IPage<School> result = schoolService.getSchoolPage(page, size, keyword, city, schoolType);
        return Result.success(result);
    }
    
    /**
     * 获取院校详情
     */
    @GetMapping("/{id}")
    public Result<School> getSchool(@PathVariable Long id) {
        School school = schoolService.getById(id);
        if (school == null) {
            return Result.error("院校不存在");
        }
        return Result.success(school);
    }
    
    /**
     * 创建院校
     */
    @PostMapping
    public Result<String> createSchool(@Valid @RequestBody School school) {
        boolean success = schoolService.createSchool(school);
        if (success) {
            return Result.success("创建成功");
        }
        return Result.error("创建失败");
    }
    
    /**
     * 更新院校信息
     */
    @PutMapping("/{id}")
    public Result<String> updateSchool(@PathVariable Long id, @Valid @RequestBody School school) {
        school.setId(id);
        boolean success = schoolService.updateSchool(school);
        if (success) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    
    /**
     * 删除院校
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteSchool(@PathVariable Long id) {
        boolean success = schoolService.deleteSchool(id);
        if (success) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
    
    /**
     * 启用/禁用院校
     */
    @PutMapping("/{id}/status")
    public Result<String> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        boolean success = schoolService.updateStatus(id, status);
        if (success) {
            return Result.success("状态更新成功");
        }
        return Result.error("状态更新失败");
    }
}